<template>
  <div class="app-container" style="justify-content: flex-start" v-if="isShow">
    <el-row :gutter="5">
      <el-col :span="19" style="border-right:1px solid #eee;">
        <el-row>
          <el-col :span="6" class="title">
            欢迎回来, {{ realName }}
          </el-col>

          <el-col :span="18">
            <el-form :model="queryWkoParams" ref="queryWkoParams" size="small" :inline="true" v-show="true"
                     class="flex-row">
              <el-form-item>
                <treeselect :multiple="false" :flat="false"
                            v-model="queryWkoParams.asgnDeptId" :options="deptOptions" :show-count="false"
                            placeholder="请选择公司"
                            :zIndex="9999" style="width: 200px;margin-right: 10px; margin-bottom: 10px;" />
              </el-form-item>

              <el-form-item label="">
                <el-date-picker
                    v-model="queryWkoParams.dateRange"
                    style="width: 240px"
                    value-format="yyyy/MM/dd"
                    type="datetimerange"
                    range-separator="-"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    @change="handleChangeDate"
                ></el-date-picker>
              </el-form-item>

              <el-form-item>
                <div style="margin-left: 20px;color: #999999;font-size: 12px;">
                  最多查询一年内数据
                </div>
              </el-form-item>

              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>

        <!-- 汇总 -->
        <el-row style="margin-top: 10px">
          <el-card class="update-log" shadow="hover" v-loading="wkordStatusLoading" style="padding-bottom: 10px">
            <el-col :span="4">
              <el-statistic
                  group-separator=","
                  :value="wkordStatus.totalNum"
                  title="工单总数">
                <template slot="prefix">
                  <i class="el-icon-s-data" style="color: red"></i>
                </template>
              </el-statistic>
            </el-col>
            <el-col :span="4">
              <el-statistic
                  group-separator=","
                  :value="wkordStatus.opSPLNum"
                  title="运管平台工单">
                <template slot="prefix">
                  <i class="el-icon-s-data" style="color: red"></i>
                </template>
              </el-statistic>
            </el-col>
            <el-col :span="4">
              <el-statistic
                  group-separator=","
                  :value="wkordStatus.callNum"
                  title="热线工单">
                <template slot="prefix">
                  <i class="el-icon-s-data" style="color: red"></i>
                </template>
              </el-statistic>
            </el-col>
            <el-col :span="4">
              <el-statistic
                  group-separator=","
                  :value="wkordStatus.nodoneNum"
                  title="待完成工单数">
                <template slot="prefix">
                  <i class="el-icon-s-data" style="color: red"></i>
                </template>
              </el-statistic>
            </el-col>
            <el-col :span="4">
              <el-statistic
                  group-separator=","
                  :value="wkordStatus.doneNum"
                  title="已完成工单数">
                <template slot="prefix">
                  <i class="el-icon-s-data" style="color: red"></i>
                </template>
              </el-statistic>
            </el-col>
          </el-card>

        </el-row>

        <!--工单数据-->
        <el-row style="margin-top:10px">
          <el-col :span="24">
            <el-card class="update-log" shadow="hover" v-loading="wkordDataLoading">
              <div slot="header" class="clearfix">
                <span>工单数据</span>
              </div>
              <div class="body el-table el-table--enable-row-hover el-table--medium">
                <div ref="wkordDataRef" style="height:300px;" />
              </div>
            </el-card>
          </el-col>
        </el-row>

        <el-row style="margin-top:10px">
          <el-col :span="12">
            <el-card class="update-log" shadow="hover" v-loading="wkordCatLoading">
              <div slot="header" class="clearfix">
                <span>工单一级类目占比</span>
              </div>
              <div class="body el-table el-table--enable-row-hover el-table--medium">
                <div ref="wkordCatRef" style="height:300px;" />
              </div>
            </el-card>
          </el-col>

          <el-col :span="12">
            <el-card class="update-log" shadow="hover" v-loading="wkordOriginLoading">
              <div slot="header" class="clearfix">
                <span>工单来源占比</span>
              </div>
              <div class="body el-table el-table--enable-row-hover el-table--medium">
                <div ref="wkordOriginRef" style="height:300px;" />
              </div>
            </el-card>
          </el-col>

        </el-row>

        <el-row style="margin-top:10px">
          <el-col :span="12">
            <el-card class="update-log" shadow="hover">
              <div slot="header" class="clearfix">
                <span>分公司工单占比</span>
              </div>
              <div ref="branchRef" style="height:300px;" />
            </el-card>
          </el-col>


          <el-col :span="12">
            <el-card class="update-log" shadow="hover" v-loading="branchLoading">
              <div slot="header" class="clearfix">
                <span>分公司工单平均万户热户占比</span>
              </div>
              <line-chart :chart-data="branchData"
                          ref="branch"
                          title="各分公司工单数量" from-type="branch">
              </line-chart>
            </el-card>
          </el-col>

        </el-row>


      </el-col>

      <el-col :span="5" style="">
        <!--        <el-row class="title">
                  平台公告
                </el-row>-->

        <!--        <el-row v-for="(item,index) in msgList" :key="index" style="padding-top: 10px">
                  {{item.msg}}
                </el-row>-->
        <el-table v-loading="loading" :data="msgList">
          <el-table-column label="平台公告" align="center" prop="title">
            <template slot-scope="scope">
              <span @click="onShowMsg(scope.row)">{{ scope.row.title }}</span>
            </template>
          </el-table-column>
        </el-table>
        <pagination
            v-show="total>0"
            :total="total"
            layout="prev, next,jumper"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />

      </el-col>
    </el-row>

    <el-dialog title="消息" :visible.sync="openMsg" width="500px" append-to-body center
               :before-close="handleCancelMsg">
      {{ mgsInfo }}
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancelMsg">关 闭</el-button>
      </div>
    </el-dialog>

    <el-dialog title="调整分公司热户数" :visible.sync="showEditPop" width="600px" append-to-body center>
      <div class="dialog-scroll" style="align-items: center">
        <div class="flex-row center-x">
          <div>名字：</div>
          <div class="flex-row center-x">
            <el-input v-model="realName" placeholder="输入数字" type="number" min="0"
                      @input="handleInput" class="match-parent" />
            <div>万户</div>
          </div>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="showEditPop=false">取消</el-button>
        <el-button type="primary" @click="">提交</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import "@/style/wkOrderList.scss";
import LineChart from '../dashboard/LineChart'
import { getMsgRecvByUserId } from "@/api/wkomsg/wkomsg.js";
import * as echarts from "echarts";
import { formatDateToStr } from "@/api/utils/dateUtil";
import {
  getWkoStatusByDateRange,
  getWkoStatsDataByDateRange,
  getWkoOriginCateByDateRange,
  getWkoIssCateByDateRange
} from "@/api/wkorder/wkoStats.js";
import { deptCompTreeCurUser } from "@/api/system/user";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Worksys",
  components: {
    LineChart,
    Treeselect
  },
  data () {
    return {
      isShow: true,
      realName: '',

      // 查询参数 工单
      queryWkoParams: {
        dateRange: undefined,
        startDate: undefined,
        endDate: undefined,
        asgnDeptId: undefined
      },
      wkordStatus: {
        totalNum: 0,
        doneNum: 0,
        nodoneNum: 0,
        opSPLNum: 0,
        callNum: 0,
      },
      msgList: [],
      loading: false,
      total: 1,
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      openMsg: false,
      mgsInfo: undefined,
      wkordStatusLoading: false,
      wkordDataLoading: false,
      wkordOriginLoading: false,
      wkordCatLoading: false,


      // 各分公司工单数量
      branchLoading: false,
      branchData: {
        nameList: ['A公司', 'B公司', 'C公司', 'D公司', 'E公司', 'F公司'],
        countList: [132, 140, 230, 100, 346, 100],
      },
      showEditPop: false,

      deptOptions: undefined,//部门
    };
  },
  created () {
    this.onInitDetpOptions();
  },
  mounted () {
    if (this.isShow) {
      this.$nextTick(() => { //DOM 加载完毕
        this.realName = this.$store.state.user.realName;
        this.onMsgRecvByUserId();
        this.onInitDate();
        this.handleQuery();
      });

    }
  },
  methods: {
    /**
     * 初始化部门树
     */
    onInitDetpOptions () {
      deptCompTreeCurUser().then(response => {
        this.deptOptions = response.data;
      });
    },
    handleInput () {

    },
    // 查询柱状图数据
    queryLineChart (type) {
      let lineChartDataName = ''
      let refName = ''
      let loadingName = ''
      switch (type) {
        case 'branch':
          lineChartDataName = 'branchData'
          refName = 'branch'
          loadingName = 'branchLoading'
          break;
        case 'branchPercent':
          break;
        case 'branchHotPercent':
          break;
        default:
          break;
      }
      //TODO 外层缺接口请求
      // 更新子组件
      this.$nextTick(() => {
        this.$refs[refName].initChart()
      })
    },
    handleQuery () {
      if (!this.queryWkoParams.endDate || !this.queryWkoParams.startDate) {
        this.$message.error("请录入查询日期");
        return
      }

      this.getWkorderStatus();
      this.getWkOrdData();
      this.getWkordoRigin();
      this.getWkordCat();

      this.getBranchOrderData();
    },
    getWkorderStatus () {
      this.wkordStatusLoading = true
      getWkoStatusByDateRange(this.queryWkoParams).then(response => {
        if (response.data) {
          this.wkordStatus = response.data
        } else {
          this.wkordStatus = this.$options.data().wkordStatus;
        }
        debugger;
        this.wkordStatusLoading = false
      });
    },

    onInitDate () {
      this.queryWkoParams.endDate = new Date();
      this.queryWkoParams.endDate.setDate(new Date().getDate());

      this.queryWkoParams.endDate = formatDateToStr(this.queryWkoParams.endDate, "yyyy-MM-dd");

      this.queryWkoParams.startDate = new Date();
      this.queryWkoParams.startDate.setDate(new Date().getDate() - 6);
      this.queryWkoParams.startDate = formatDateToStr(this.queryWkoParams.startDate, "yyyy-MM-dd");

      this.queryWkoParams.dateRange = [this.queryWkoParams.startDate, this.queryWkoParams.endDate]
    },

    getList () {
      this.onMsgRecvByUserId()();
    },

    /**
     *
     */
    getBranchOrderData () {

      let wkordDataEchart = echarts.init(this.$refs.branchRef, "macarons"); //macarons 主题

      wkordDataEchart.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        legend: {
          data: ['工单数量', '工单占比']
        },
        xAxis: [
          {
            type: 'category',
            data: ['A公司', 'B公司', 'C公司', 'D公司', 'E公司', 'F公司']
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '',
            // min: 0,
            // max: 250,
            // interval: 50,
            axisLabel: {}
          },
          {
            type: 'value',
            name: '',
            // min: 0,
            // max: 25,
            // interval: 5,
            // axisLabel: {
            //   formatter: '{value} °C'
            // }
          }
        ],
        series: [
          {
            name: '工单数量',
            type: 'bar',  // 柱状图
            data: [1, 0, 2, 1, 0, 2]
          },

          {
            name: '工单占比',
            type: 'line',  // 折线图
            yAxisIndex: 1,  // 使用第二个Y轴
            data: [16, 0, 32, 16, 0, 32]
          }
        ]
      });
    },

    getWkOrdData () {
      this.wkordDataLoading = true;

      getWkoStatsDataByDateRange(this.queryWkoParams).then((res) => {
        this.wkordDataLoading = false;
        //let resultList=response.data;
        let maxNum = 300;
        let data = [];//[["2000-06-05", 116], ["2000-06-06", 129], ["2000-06-07", 135], ["2000-06-08", 86], ["2000-06-09", 73], ["2000-06-10", 85], ["2000-06-11", 73], ["2000-06-12", 68], ["2000-06-13", 92], ["2000-06-14", 130], ["2000-06-15", 245], ["2000-06-16", 139], ["2000-06-17", 115], ["2000-06-18", 111], ["2000-06-19", 309], ["2000-06-20", 206], ["2000-06-21", 137], ["2000-06-22", 128], ["2000-06-23", 85], ["2000-06-24", 94], ["2000-06-25", 71], ["2000-06-26", 106], ["2000-06-27", 84], ["2000-06-28", 93], ["2000-06-29", 85], ["2000-06-30", 73], ["2000-07-01", 83], ["2000-07-02", 125], ["2000-07-03", 107], ["2000-07-04", 82], ["2000-07-05", 44], ["2000-07-06", 72], ["2000-07-07", 106], ["2000-07-08", 107], ["2000-07-09", 66], ["2000-07-10", 91], ["2000-07-11", 92], ["2000-07-12", 113], ["2000-07-13", 107], ["2000-07-14", 131], ["2000-07-15", 111], ["2000-07-16", 64], ["2000-07-17", 69], ["2000-07-18", 88], ["2000-07-19", 77], ["2000-07-20", 83], ["2000-07-21", 111], ["2000-07-22", 57], ["2000-07-23", 55], ["2000-07-24", 60]];

        let list = res.data;
        for (let i = 0; i < list.length; i++) {
          let d = [];
          d.push(list[i].statsTime)
          d.push(list[i].totalNum)

          data.push(d)
        }


        const dateList = data.map(function (item) {
          return item[0];
        });
        const valueList = data.map(function (item) {
          return item[1];
        });
        let wkordDataEchart = echarts.init(this.$refs.wkordDataRef, "macarons"); //macarons 主题

        wkordDataEchart.setOption({
          // Make gradient line here
          visualMap: [
            {
              show: false,
              type: 'continuous',
              seriesIndex: 0,
              min: 0,
              max: maxNum,

              inRange: {
                color: ['#29b8f6', '#2990f6', '#293af6'],
              }
            }
          ],
          title: [
            {
              left: 'left',
              text: ''
            }
          ],
          legend: {
            data: ['热线工单', '运管工单']
          },
          tooltip: {
            trigger: 'axis'
          },
          xAxis: [
            {
              data: dateList
            }
          ],
          yAxis: [
            {}
          ],
          grid: [
            {
              bottom: '10%'
            }
          ],
          series: [
            {
              name: "热线工单",
              type: 'line',
              showSymbol: true,//曲线上展示点
              data: valueList,
              smooth: true,//平滑曲线
              areaStyle: {
                color: {
                  type: 'linear',
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: [{
                    offset: 0, color: 'rgba(46, 199, 201, 0.3)' // 边界渐变色
                  }, {
                    offset: 1, color: 'rgba(46, 199, 201, 0)' // 渐变到透明
                  }]
                }
              },
            },
            {
              name: '运管工单',
              type: 'line',
              data: [2, 8, 1, 3, 2],
              smooth: true,//平滑曲线
              areaStyle: {
                color: {
                  type: 'linear',
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: [{
                    offset: 0, color: 'rgba(182,162,222, 0.3)' // 边界渐变色
                  }, {
                    offset: 1, color: 'rgba(182,162,222, 0)' // 渐变到透明
                  }]
                }
              },
            }
          ]
        });
      })

    },
    getWkordoRigin () {
      this.wkordOriginLoading = true;

      getWkoOriginCateByDateRange(this.queryWkoParams).then((res) => {
        this.wkordOriginLoading = false;

        let list = res.data;

        /*let dataOrigin=[
            { value: 1048, name: '12345' },
            { value: 735, name: '运营平台' },
            { value: 580, name: '热线电话' },
          ]*/
        let dataOrigin = []

        for (let i = 0; i < list.length; i++) {
          let obj = {
            value: list[i].totalNum,
            name: list[i].statsCate
          }
          dataOrigin.push(obj);
        }

        let wkordRiginEchart = echarts.init(this.$refs.wkordOriginRef, "macarons"); //macarons 主题
        wkordRiginEchart.setOption({
          title: {
            text: '',
            subtext: '',
            left: 'center'
          },
          tooltip: {
            trigger: 'item'
          },
          legend: {
            orient: 'vertical',
            left: 'left'
          },
          series: [
            {
              name: '工单来源',
              type: 'pie',
              radius: ['40%', '70%'],
              data: dataOrigin,
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        })

      })

    },
    getWkordCat () {
      this.wkordCatLoading = true;
      this.wkordCatLoading = false;

      getWkoIssCateByDateRange(this.queryWkoParams).then((res) => {

        let list = res.data;

        /*let dataOrigin=[
            { value: 1048, name: '12345' },
            { value: 735, name: '运营平台' },
            { value: 580, name: '热线电话' },
          ]*/
        let dataCate = []

        for (let i = 0; i < list.length; i++) {
          let obj = {
            value: list[i].totalNum,
            name: list[i].statsCate
          }
          dataCate.push(obj);
        }

        let echart = echarts.init(this.$refs.wkordCatRef, "macarons"); //macarons 主题
        echart.setOption({
          title: {
            text: '',
            subtext: '',
            left: 'center'
          },
          tooltip: {
            trigger: 'item'
          },
          // legend: {
          //   orient: 'vertical',
          //   left: 'center',
          //   bottom: 0,
          // },
          legend: {
            orient: 'vertical',
            left: 'left'
          },
          series: [
            {
              name: '一级类目',
              type: 'pie',
              radius: ['40%', '70%'],
              data: dataCate,
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        })

      });


    },

    onMsgRecvByUserId () {
      debugger;
      getMsgRecvByUserId(this.queryParams).then((res) => {
        this.msgList = res.data;
        this.total = Number(res.total);
      })
    },
    onShowMsg (row) {
      console.log(row.msg)
      this.openMsg = true;
      this.mgsInfo = row.msg;
    },
    handleCancelMsg () {
      this.openMsg = false;
      this.mgsInfo = undefined;
    },

    /**
     * 日期改变触发
     * @param value
     */
    handleChangeDate (value) {
      if (value) {
        this.queryWkoParams.startDate = value[0];
        this.queryWkoParams.endDate = value[1];
      } else {
        this.queryWkoParams.startDate = undefined;
        this.queryWkoParams.endDate = undefined;
      }
    },
  },
  computed: {}
};
</script>

<style scoped lang="scss">
@import "../../assets/styles/common.scss";

.title {
  font-size: 24px;
}
</style>

